package com.monkeyk.sos.util;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;

public abstract class WebUtils {
    //private
    private WebUtils() {
    }

    /**
     * Retrieve client ip address
     *
     * @param request HttpServletRequest
     * @return IP
     */
    public static String retrieveClientIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (isUnAvailableIp(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (isUnAvailableIp(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (isUnAvailableIp(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    private static boolean isUnAvailableIp(String ip) {
        return (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip));
    }

    /*
     * 获得随机十位数字字符串
     */
    public static String getRandomString(){
        return String.valueOf(new Random().nextInt(899999)+1000000000);
    }
    
    
    /*
     * web应用添加<meta>标签验证
     */
    public static boolean checkWebOwner(String url,String property,String content) {
    	boolean flag= false;
    	Document doc = null;
		try {
			doc = Jsoup.connect(url).get();
		} catch (IOException e) {
			return flag;
		}
		Elements meta = doc.select("meta");
		for (Element src : meta) {
			if (src.attr("property").equals(property)) {
				if(src.attr("content").equals(content)){
					flag = true;
					break;
				}
			}
		};
		return flag;
	}
    
    
    
    public static void writeJSON(HttpServletResponse response, Object obj)  {
		response.setContentType("application/json;charset=utf-8");
		ObjectMapper mapper = new ObjectMapper();
		JsonFactory factory = mapper.getFactory();
		JsonGenerator responseJsonGenerator = null;
		try {
			responseJsonGenerator = factory.createGenerator(response.getOutputStream(), JsonEncoding.UTF8);
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			responseJsonGenerator.writeObject(obj);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
    
    public static String md5(String passWord) {     
        Md5PasswordEncoder md5 = new Md5PasswordEncoder();     
        // false 表示：生成32位的Hex版, 这也是encodeHashAsBase64的, Acegi 默认配置; true  表示：生成24位的Base64版   
        md5.setEncodeHashAsBase64(false);     
        return md5.encodePassword(passWord, null);
    }  
    public static void sha_256() throws NoSuchAlgorithmException {       
        ShaPasswordEncoder sha = new ShaPasswordEncoder(256);     
        sha.setEncodeHashAsBase64(true);     
        String pwd = sha.encodePassword("1234", null);     
        System.out.println("哈希算法 256: " + pwd + " len=" + pwd.length());     
    }     
         
        
    public static void sha_SHA_256() {     
        ShaPasswordEncoder sha = new ShaPasswordEncoder();     
        sha.setEncodeHashAsBase64(false);     
        String pwd = sha.encodePassword("1234", null);      
        System.out.println("哈希算法 SHA-256: " + pwd + " len=" + pwd.length());     
    }     
         
        
    public static void md5_SystemWideSaltSource () {     
        Md5PasswordEncoder md5 = new Md5PasswordEncoder();     
        md5.setEncodeHashAsBase64(false);     
             
        // 使用动态加密盐的只需要在注册用户的时候将第二个参数换成用户名即可     
        String pwd = md5.encodePassword("1234", "acegisalt");     
        System.out.println("MD5 SystemWideSaltSource: " + pwd + " len=" + pwd.length());     
    }     
    
    /**
    * @Title: sendEmai 
    * @Description: 发送邮件，返回验证码 
    * @param @param eamil
    * @param @return    设定文件 
    * @return String    返回类型 
    * @throws
     */
    public static Map<String, String> sendEmaiCheck(String eamil,JavaMailSenderImpl javaMail) {
    	Map<String, String> result = new HashMap<String, String>();
    	String code = String.valueOf(new Random().nextInt(899999)+100000);//随机生成6位验证码
    	result.put("code", code);
		String message = "您的邮箱验证码是："+code+"。有效期60秒，请及时验证！" ; //邮件内容
		String failMess = "";//错误信息
		try {
			JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
			senderImpl.setHost(javaMail.getHost().trim());//发件服务器地址
			senderImpl.setUsername(javaMail.getUsername().trim());//发件用户名
			senderImpl.setPassword(javaMail.getPassword().trim());//发件用户密码
			SimpleMailMessage smm = new SimpleMailMessage();  
			// 设定邮件参数  
			smm.setFrom(javaMail.getJavaMailProperties().getProperty("sendFrom"));  
			smm.setTo(eamil.trim());  
			smm.setSubject("腾邦邮件验证");  
			smm.setText(message);  
			// 发送邮件  
			senderImpl.send(smm);
		} catch (Exception e) {
			e.printStackTrace();
			failMess=e.getMessage();
		}finally{
			if(failMess.indexOf("Mail server connection failed") >= 0){
				result.put("failMess", "邮件服务器连接失败，请核实！");
			}else if (failMess != "") {
				result.put("failMess", "请核实邮箱信息！");
			}else {
				result.put("failMess", failMess);
			}
		};
		return result;
	}
    
    
    /**
    * @Title: sendMsg 
    * @Description: 发送短信消息  
    * @param @param phones
    * @param @param content
    * @param @return    设定文件 
    * @return String    返回类型 
    * @throws
     */
    public static Map<String, String> sendMsg(String phones){
    	Config config = new Config("phoneInformation.properties");
    	String code = String.valueOf(new Random().nextInt(899999)+100000);//随机生成6位验证码
		String content = "尊敬的用户，您的验证码为" + code + "，有效期为60秒，如有疑虑请详询"+config.getConfigValue("phone.customer.service")+"（客服电话）【腾邦服务中心】";
    	//短信接口URL提交地址
		String url = config.getConfigValue("phone.url");
	/*	Map<String, String> params = new HashMap<String, String>();
		params.put("zh", config.getConfigValue("phone.zh"));
		params.put("mm", config.getConfigValue("phone.mm"));
		params.put("dxlbid", config.getConfigValue("phone.dxlbid"));
		params.put("extno", config.getConfigValue("phone.extno"));
		//手机号码，多个号码使用英文逗号进行分割
		params.put("hm", phones);
		//将短信内容进行URLEncoder编码
		try {
			params.put("nr", URLEncoder.encode(content, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}*/
		Map<String, String> map= new HashMap<String, String>();
		/*map.put("status", HttpRequestUtil.getRequest(url, params));
		map.put("code", code);*/
		map.put("status", "");
		map.put("code", code);
		return map;
	}
    
    public static void main(String[] args) {
    	sendMsg("18682112087");
	}
}